package com.android.fragmentdemo.thread13

import org.junit.Test
import java.util.concurrent.locks.ReentrantLock

class Demo13 {
    @Test
    fun testRunnable() {

        val lock1 = ReentrantLock()
        val lock2 = ReentrantLock()
        val thread1 = Thread(ThreadTest(lock1, lock2), "thread1")
        val thread2 = Thread(ThreadTest(lock2, lock1), "thread2")
        thread1.start()
        thread2.start()

        thread1.interrupt()

        Thread.sleep(5 * 1000)
    }

    class ThreadTest(lock1: ReentrantLock, lock2: ReentrantLock) : Runnable {
        private val mLock1 = lock1
        private val mLock2 = lock2
        override fun run() {
            try {
                mLock1.lockInterruptibly()
                Thread.sleep(500)
                mLock2.lockInterruptibly()
            } catch (ex: InterruptedException) {
                ex.printStackTrace()
            } finally {
                mLock1.unlock()
                mLock2.unlock()
                println("${Thread.currentThread().name}获取到了锁")
            }
        }
    }

}